# -*- coding: utf-8 -*-
"""
    moe.wiki.path
    ~~~~~~~~~~~~~

    Wiki path utilities.

    :copyright: 2009 by tipfy.org.
    :license: BSD, see LICENSE.txt for more details.
"""
from werkzeug import cached_property

from tipfy import current_app

from moe.utils import inflection


class WikiPath(object):
    """Helper to normalize and validate a wiki URL path and get path parts."""
    def __init__(self, path, endpoint=None):
        self.endpoint = endpoint
        self._parts = []
        if path:
            parts = path.strip('/').split('/')
            for part in parts:
                if len(self._parts) == self.max_path_depth:
                    break

                part = part.strip()
                if part:
                    self._parts.append(part)

    @cached_property
    def protected_path(self):
        return current_app.get_config('moe.wiki', 'protected_path')

    @cached_property
    def start_page(self):
        return current_app.get_config('moe.wiki', 'start_page') + '/'

    @cached_property
    def max_path_depth(self):
        return current_app.get_config('moe.wiki', 'max_path_depth')

    @cached_property
    def path_parts(self):
        return [inflection.camel_to_dashes(part) for part in self._parts]

    @cached_property
    def normalized_path(self):
        return '/'.join(self.path_parts) + '/'

    @cached_property
    def page_name(self):
        if self._parts:
            return self.get_page_name(self._parts[-1])

    @cached_property
    def all_paths(self):
        all_paths = []
        path = ''
        for part in self.path_parts:
            path += part + '/'
            all_paths.append(path)

        return all_paths

    @cached_property
    def parent_paths(self):
        return self.all_paths[:-1]

    @cached_property
    def parent_path(self):
        if self.parent_paths:
            return self.parent_paths[-1]

    @cached_property
    def breadcrumbs(self):
        res = []

        if not (self.endpoint == 'wiki/index' and self.is_start_path()):
            # Add all pages except the initial one in view mode.
            for path in self.all_paths:
                name = self.get_page_name(path.rstrip('/').rsplit('/', 1)[-1])
                res.append((path, name))

        return res

    def is_valid_path(self):
        """Checks if the path is using the protected path."""
        if self.path_parts and self.path_parts[0] == self.protected_path:
            return False

        return True

    def is_start_path(self):
        return (self.normalized_path == self.start_page)

    def get_page_name(self, normalized_path_part):
        return ' '.join(normalized_path_part.split('-')).title()
